package com.cinema.api.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cinema.api.constant.Roles;
import com.cinema.api.model.entity.Role;
import com.cinema.api.mapper.RoleMapper;
import com.cinema.api.model.exception.BizException;
import com.cinema.api.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cinema.api.utils.BaseUtil;
import com.cinema.api.utils.DataTimeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhh
 * @since 2021-12-31
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    /**
     * 根据workerId查询对应权限
     */
    @Override
    public List<Role> findRoleListById(String wid) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.in("wid", wid)
                .eq("is_delete", 0)
                .ne("value", "ROLE_WORKER");
        List<Role> roles = roleMapper.selectList(wrapper);
        return roles;
    }

    /**
     * 根据Id删除对应权限
     */
    @Override
    public void deleteById(String id) throws Exception {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.in("id", id)
                .eq("is_delete", 0);
        Role role = roleMapper.selectOne(wrapper);
        if (role.getValue().equals(Roles.ROLE_WORKER)) {
            throw new BizException(20043, "员工基本权限不能删除!");
        }
        roleMapper.deleteById(id);
     }

    /**
     * 为员工添加权限
     */
    @Override
    public void add(Role role) throws Exception {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.in("wid", role.getWid())
                .in("value", role.getValue());
        Role roleOne = roleMapper.selectOne(wrapper);
        if (BaseUtil.isNotEmpty(roleOne)) {
            throw new BizException(20043, "该员工已拥有该权限, 请不要重复添加");
        }
        role.setId(UUID.randomUUID().toString());
        role.setCreateTime(DataTimeUtil.getNowTimeString());
        role.setIsDelete(0);
        roleMapper.insert(role);
    }

    /**
     *  根据workerId删除其所有权限
     */
    @Override
    public void deleteAllByWID(String wid) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.in("wid", wid);
        roleMapper.delete(wrapper);
    }
}
